<?php

namespace Admin\Model\Business;

use Admin\Model\AbstractTable\Usuario as Table;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Select;

class Usuario
{

    protected $_adapter;

    public function __construct( Adapter $adapter )
    {
        $this->_adapter = $adapter;

    }

    public function grid( $page )
    {
        $select = new \Zend\Db\Sql\Select();
        $select->from( 'usuario' )->order( 'login' );

        $adapter   = new \Zend\Paginator\Adapter\DbSelect( $select, $this->_adapter, $this->resultSetPrototype );
        $paginator = new \Zend\Paginator\Paginator( $adapter );
        $paginator->setItemCountPerPage( 10 );
        $paginator->setCurrentPageNumber( $page );
        return $paginator;

    }

    public function report()
    {
        $table = new Table( $this->_adapter );
        return $table->fetchAll();
    }

    public function insert( $data )
    {

        $loginTable = new Table( $this->_adapter );

        try {
            $this->_adapter->getDriver()->getConnection()->beginTransaction();
            $data['senha'] = md5( $data['senha'] );
            $loginTable->inserir( $data );
            $this->_adapter->getDriver()->getConnection()->commit();
        } catch (\Exception $e) {
            $this->_adapter->getDriver()->getConnection()->rollback();
            throw new \Admin\Exception( 'Erro ao salvar usuário' );
        }

    }

    public function listarDadosUsuario( $id )
    {
        $loginTable = new Table( $this->_adapter );
        return $loginTable->fetchRow( array('id = ?' => $id) );

    }

    public function atualizar( $data )
    {
        $loginTable = new Table( $this->_adapter );

        try {
            $this->_adapter->getDriver()->getConnection()->beginTransaction();
            $data['senha'] = md5( $data['senha'] );
            $id            = $data['id'];
            $loginTable->updateUsuario( $data, $id );
            $this->_adapter->getDriver()->getConnection()->commit();
        } catch (\Exception $e) {
            $this->_adapter->getDriver()->getConnection()->rollback();
            throw new \Admin\Exception( 'Erro ao salvar usuário' );
        }

    }

    public function excluir( $id )
    {
        $loginTable = new Table( $this->_adapter );

        try {
            $this->_adapter->getDriver()->getConnection()->beginTransaction();
            $loginTable->excluir( $id );
            $this->_adapter->getDriver()->getConnection()->commit();
        } catch (\Exception $e) {
            $this->_adapter->getDriver()->getConnection()->rollback();
            throw new \Admin\Exception( 'Erro ao excluir usuário' );
        }

    }

}
